package com.kun.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.kun.entity.SysDept;
import com.kun.service.SysDeptService;
import com.kun.util.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门管理
 *
 * @author kun.li
 */
@RestController
@RequestMapping("dept")
@RequiredArgsConstructor
@Tag(name = "部门管理")
public class DeptController {
    private final SysDeptService sysDeptService;

    @Operation(summary = "获取部门树")
    @GetMapping("getDeptTableTree")
    public ResponseResult<List<Tree<String>>> getDeptTableTree() {
        List<SysDept> sysDeptList = sysDeptService.list();
        List<Tree<String>> treeList = TreeUtil.build(sysDeptList, "-1", (sysDept, tree) -> {
            tree.setId(sysDept.getDeptId());
            tree.setParentId(sysDept.getParentId());
            tree.setName(sysDept.getDeptName());
            tree.setWeight(sysDept.getWeight());
            tree.putExtra("createTime", DateUtil.formatDateTime(sysDept.getCreateTime()));
        });
        return ResponseResult.success(treeList);
    }

    @Operation(summary = "部门保存")
    @PostMapping("save")
    public ResponseResult<Boolean> save(@RequestBody SysDept sysDept) {
        return ResponseResult.success(sysDeptService.save(sysDept));
    }
    @Operation(summary = "部门编辑")
    @PostMapping("update")
    public ResponseResult<Boolean> update(@RequestBody SysDept sysDept) {
        return ResponseResult.success(sysDeptService.updateById(sysDept));
    }
    @Operation(summary = "部门级联删除")
    @DeleteMapping("delete/{deptId}")
    public ResponseResult<Boolean> delete(@PathVariable String deptId) {
        // 判断该部门下是否还有子部门 如果有进行迭代删除
        List<SysDept> sysDepts = sysDeptService.list();
        List<SysDept> resDeptList = new ArrayList<>();
        recursiveDept(sysDepts, deptId, resDeptList);
        resDeptList.addAll(sysDepts.stream()
                .filter(sysDept -> deptId.equals(sysDept.getDeptId())).toList());
        resDeptList.forEach(sysDept -> sysDeptService.removeById(sysDept.getDeptId()));
        return ResponseResult.success(Boolean.TRUE);
    }


    /**
     * 递归查询所有子节点。
     * @param allDeptList 所有部门列表
     * @param parentId 父部门ID
     * @param resDeptList 结果集合
     */
    private void recursiveDept(List<SysDept> allDeptList, String parentId, List<SysDept> resDeptList) {
        // 使用 Stream API 进行筛选和遍历
        allDeptList.stream().filter(sysDept -> sysDept.getParentId().equals(parentId)).forEach(sysDept -> {
            resDeptList.add(sysDept);
            recursiveDept(allDeptList, sysDept.getDeptId(), resDeptList);
        });
    }

}
